import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/',
      component: () => import('@/views/AppLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        // 管理员路由
        {
          path: 'admin/bicycles',
          name: 'admin-bicycles',
          component: () => import('@/views/admin/BicyclesView.vue'),
          meta: { role: 'admin' },
        },

        {
          path: 'admin/maintenance',
          name: 'admin-maintenance',
          component: () => import('@/views/admin/MaintenanceView.vue'),
          meta: { role: 'admin' },
        },
        {
          path: 'admin/statistics',
          name: 'admin-statistics',
          component: () => import('@/views/admin/StatisticsView.vue'),
          meta: { role: 'admin' },
        },

        // 学生路由
        {
          path: 'student/borrow',
          name: 'student-borrow',
          component: () => import('@/views/student/BorrowView.vue'),
          meta: { role: 'student' },
        },
        {
          path: 'student/report',
          name: 'student-report',
          component: () => import('@/views/student/ReportView.vue'),
        },
      ],
    },
    // 将未匹配的路由重定向到首页
    {
      path: '/:pathMatch(.*)*',
      redirect: '/',
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth !== false)

  // 检查用户是否已登录
  if (requiresAuth && !userStore.isLoggedIn) {
    // 未登录，重定向到登录页
    next({ name: 'login' })
  } else if (to.meta.role && userStore.userInfo?.role !== to.meta.role) {
    // 检查用户角色权限
    next({ name: 'home' }) // 如果角色不匹配，重定向到首页
  } else {
    // 已登录或不需要登录的页面，正常访问
    next()
  }
})

export default router
